package com.comment.config.dao.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.jetbrains.annotations.NotNull;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class KV_LongInteger_Handler extends BaseTypeHandler<Map<Long, Integer>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<Long, Integer> parameter, JdbcType jdbcType) throws SQLException {
        StringBuilder sb = getStringBuilder(parameter);
        ps.setString(i, sb.toString());
    }


    @Override
    public Map<Long, Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String serialized = rs.getString(columnName);
        return getLongIntegerMap(serialized);
    }

    @Override
    public Map<Long, Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String serialized = rs.getString(columnIndex);
        return getLongIntegerMap(serialized);
    }

    @Override
    public Map<Long, Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String serialized = cs.getString(columnIndex);
        return getLongIntegerMap(serialized);
    }

    private static Map<Long, Integer> getLongIntegerMap(String serialized) {
        if (serialized==null||!serialized.contains("&")) {
            return new HashMap<>();
        }
        if (!serialized.contains(",")) {
            serialized = serialized + ",";
        }

        Map<Long, Integer> map = new HashMap<>();
        String[] split = serialized.split(",");
        for (String s : split) {
            String[] split1 = s.split("&");
            map.put(Long.valueOf(split1[0]), Integer.valueOf(split1[1]));
        }
        return map;
    }

    private static @NotNull StringBuilder getStringBuilder(Map<Long, Integer> parameter) {
        StringBuilder sb = new StringBuilder();
        parameter.forEach((k, v) -> sb.append(",").append(k).append("&").append(v));
        return sb;
    }
}
